﻿// <copyright file="LocalReportViewer.cs" company="Todd Aspeotis">
//  Copyright © 2011 Todd Aspeotis
// </copyright>

namespace LocalReportsEngine.UserInterface
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using LocalReportsEngine.ReportDefinitionElements;
    using LocalReportsEngine.Providers;
    using LocalReportsEngine.ExtensionMethods;
    using Microsoft.Reporting.WinForms;

    /// <summary>
    /// Renders a report and provides controls to interact with the report.
    /// </summary>
    public partial class LocalReportViewer : UserControl
    {
        protected ReportElement reportElement;

        public Dictionary<string, object> DataSets { get; set; }

        public Dictionary<string, object> DataSources { get; set; }

        /// <summary>
        /// Initializes a new instance of the LocalReportViewer class.
        /// </summary>
        public LocalReportViewer()
            : base()
        {
            this.InitializeComponent();
        }

        public void LoadReportDefinition(string path)
        {
            this.Reset();

            using (StreamReader reader = new StreamReader(path))
            {
                this.rvControl.LocalReport.LoadReportDefinition(reader);
            }

            this.reportElement = ReportElement.Load(path);
        }

        public void LoadData()
        {
            ResolveDataArgs args = new ResolveDataArgs();
            args.DataSets = this.DataSets;
            args.DataSources = this.DataSources;
            args.EventSender = this;
            // args.OnXyz
            args.ReportElement = this.reportElement;

            ProvidersFactory.ResolveData(args);

            foreach (var kvp in this.DataSets)
            {
                if (this.rvControl.LocalReport.DataSources.Any(d => d.Name.SafeEquals(kvp.Key)))
                {
                    continue;
                }

                this.rvControl.LocalReport.DataSources.Add(new ReportDataSource(kvp.Key, kvp.Value));
            }
        }

        public void RefreshReport()
        {
            this.rvControl.RefreshReport();
        }

        public void Reset()
        {
            this.DataSets = new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase);
            this.DataSources = new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase);
            this.reportElement = null;
            this.rvControl.Reset();
        }
    }
}
